#!/bin/bash

# 发版前API端点自检脚本
# 用途: 在构建产物中检查所有HTTP/HTTPS端点，确保没有写死的私网地址或旧域名
# 使用方法: 
#   1. 先执行构建: npm run build 或 vite build
#   2. 运行此脚本: bash scripts/grep-api.sh
#   3. 检查输出，确认只包含预期的端点

echo "=== 发版前API端点自检 ==="
echo "检查目录: dist/"

if [ ! -d "dist" ]; then
    echo "❌ 错误: dist 目录不存在，请先执行构建命令"
    exit 1
fi

echo ""
echo "🔍 搜索所有 HTTP/HTTPS 端点..."

# 排除常见第三方CDN域名的模式
EXCLUDE_PATTERNS=(
    "googleapis.com"
    "gstatic.com" 
    "unpkg.com"
    "jsdelivr.net"
    "cdnjs.com"
    "github.com"
    "element-plus.org"
    "w3.org"
    "mozilla.org"
    "microsoft.com"
    "apple.com"
)

echo ""
echo "📊 HTTP/HTTPS 端点统计:"
echo "========================="

# 搜索并统计所有HTTP/HTTPS端点
TEMP_FILE=$(mktemp)
grep -r -o -h "https\?://[^\"')\s]*" dist/ 2>/dev/null | sort | uniq -c | sort -nr > "$TEMP_FILE"

# 显示结果
if [ -s "$TEMP_FILE" ]; then
    while read -r line; do
        count=$(echo "$line" | awk '{print $1}')
        url=$(echo "$line" | awk '{print $2}')
        
        # 检查是否为需要关注的URL
        should_highlight=false
        if [[ "$url" == *"192.168."* ]] || [[ "$url" == *"10."* ]] || [[ "$url" == *"172."* ]]; then
            should_highlight=true
            echo "⚠️  $count 次 - $url (私网地址)"
        elif [[ "$url" == *"localhost"* ]] || [[ "$url" == *"127.0.0.1"* ]]; then
            should_highlight=true
            echo "⚠️  $count 次 - $url (本地地址)"
        elif [[ "$url" == *"47.108.58.48"* ]]; then
            should_highlight=true
            echo "⚠️  $count 次 - $url (旧服务器地址)"
        else
            # 检查是否为第三方CDN
            is_third_party=false
            for pattern in "${EXCLUDE_PATTERNS[@]}"; do
                if [[ "$url" == *"$pattern"* ]]; then
                    is_third_party=true
                    break
                fi
            done
            
            if [ "$is_third_party" = true ]; then
                echo "✅ $count 次 - $url (第三方CDN)"
            else
                echo "🔍 $count 次 - $url"
            fi
        fi
    done < "$TEMP_FILE"
else
    echo "✅ 未发现任何HTTP/HTTPS端点"
fi

echo ""
echo "========================="

# 特别检查预期的生产地址
EXPECTED_PROD_URL="http://114.67.64.10"
prod_count=$(grep -r -o "$EXPECTED_PROD_URL" dist/ 2>/dev/null | wc -l)
echo "📋 预期生产地址统计:"
echo "   $EXPECTED_PROD_URL: $prod_count 次"

# 清理临时文件
rm -f "$TEMP_FILE"

echo ""
echo "🎯 检查完成!"
echo ""
echo "💡 验收建议:"
echo "   1. 确认没有私网地址 (192.168.x.x, 10.x.x.x, 172.x.x.x)"
echo "   2. 确认没有旧服务器地址 (47.108.58.48)"
echo "   3. 确认生产地址 ($EXPECTED_PROD_URL) 出现次数合理"
echo "   4. 第三方CDN地址可以忽略"

